const mongoose = require('mongoose');
const rp = require("request-promise")
const get = async ({ curpage, eachPage }) => {
    const result = {
        curpage: ~~curpage,
        eachPage: ~~eachPage,
        total: 0,
        maxPage: 0,
        rows: []
    }
    const orderModel = mongoose.model("shop-orders")
    result.total = await orderModel.countDocuments();
    result.maxPage = Math.ceil(result.total / result.eachPage)
    result.rows = await orderModel
        .find()
        .populate("userId")
        .populate("shopId")
        .populate("distributionId")
        .skip((result.curpage - 1) * result.eachPage)
        .limit(result.eachPage)
        .exec()
    return result
}
const getDistribution = async (storeId) => await mongoose.model("shop-distribution").find({ storeId });

const addOrder = async ({
    userId,
    shopId,
    distributionId,
    goodsArr,
    state,
    price
}) => {
    let time = "";
    let y = new Date().getFullYear();
    let m = new Date().getMonth() + 1;
    let d = new Date().getDate();
    let h = new Date().getHours();
    let min = new Date().getMinutes();
    let s = new Date().getSeconds();

    time = `${y}-${m}-${d} ${h}:${min}:${s}`;


    const data = await mongoose.model("shop-orders").create({
        userId,
        shopId,
        distributionId,
        goodsArr,
        state,
        price,
        time,
    });
    return data;
};

const cha = async ({ _id }) => {
    const orderModel = mongoose.model("shop-orders");
    return await orderModel.find({
        _id: _id
    })
        .populate("userId")
        .populate("shopId")
        .populate("distributionId")
        ;
}

module.exports = { get, getDistribution, addOrder, cha }
